<?php


namespace app\back\model;


use \Exception;
use think\facade\Db;
use \think\response\Json;

class GoodsUnitModels
{
    private static $_table = 'goods_unit'; // 商品单位

    /**获取列表
     * @param $input
     * @param $info
     * @return Json
     */
    public static function list($input, $info)
    {
        try {
            $map = [];
            if ($input['type'] !== '') {
                $map[] = ['type', '=', $input['type']];
            }
            if ($input['name'] !== '') $map[] = ['name', 'like', "%{$input['name']}%"];
            $field = 'id,name,type,create_time';
            $table = Db::table(self::$_table)->where($map)->field($field);
            $count = $table->count();
            if ($count == 0) return jsonSuccess('暂无数据', ['count' => 0, 'list' => []]);
            $list = $table->page($input['page'], $input['limit'])->order('create_time', 'desc')->select()->toArray();
            return jsonSuccess('获取成功', ['count' => $count, 'list' => $list]);
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**添加
     * @param $input
     * @return Json
     */
    public static function add($input)
    {
        try {
            $input['create_time'] = time();
            $rtn = Db::table(self::$_table)->insert($input);
            if ($rtn === 1) return jsonSuccess('添加成功');
            return jsonFail('添加失败');
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**获取单个信息
     * @param $input
     * @return Json
     */
    public static function getOnly($input)
    {
        try {
            $rtn = Db::table(self::$_table)->field('id,name,type')->where('id',  $input['id'])->find();
            if ($rtn) return jsonSuccess('获取成功', $rtn);
            return jsonFail('未找到数据');
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**编辑
     * @param $input
     * @return Json
     */
    public static function edit($input)
    {
        try {
            $id = $input['id'];
            unset($input['id']);
            $rtn = Db::table(self::$_table)->where('id', $id)->update($input);
            if ($rtn) return jsonSuccess('编辑成功');
            return jsonFail('编辑失败');
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**删除
     * @param $input
     * @return Json
     */
    public static function del($input)
    {
        try {
            $rtn = Db::table(self::$_table)->where('id', $input['id'])->delete();
            if ($rtn) return jsonSuccess('删除成功');
            return jsonFail('删除失败');
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }
}